
import React from "react";
import moment from "moment";
import {DatePicker, Form, Input} from "antd";

/**
 * 年份范围选择框
 */
class FormYearRangePicker extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            mode: ['year', 'year'],
            value: [],
        }
    }

    handlePanelChange = (value, mode) => {
        let dateString = [moment(value[0]).format(this.props.format ? this.props.format : "YYYY"),moment(value[1]).format(this.props.format ? this.props.format : "YYYY")];
        let obj = {};
        obj[this.props.field ? this.props.field : "default_year_range_picker"] = dateString;
        this.props.form.setFieldsValue(obj);
        this.setState({
            value
        });
    };

    handleChange = value => {
        this.setState({ value });
    };

    handleOpenChange = (open,reset,changeReset) => {
        if (open && reset){
            this.setState({value:[]});
            changeReset();
        }
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const { RangePicker } = DatePicker;
        const { value, mode } = this.state;
        const {label,field,rules,disabled,placeholder,start,end,reset,changeReset} = this.props;
        let defaultValue = [start ? moment(start) : null,end ? moment(end) : null];
        return (
            <Form.Item label={label ? label : "年份范围选择"}>
                {getFieldDecorator(field ? field : 'default_year_range_picker', {initialValue: "",rules: rules ? rules : []})(
                    <Input type={"hidden"}>
                    </Input>
                )}
                <RangePicker
                    style={{width:438}}
                    placeholder={Array.isArray(placeholder) ? placeholder : ['开始年份', '结束年份']}
                    disabled={disabled ? disabled : false}
                    format="YYYY"
                    value={reset === true ? [] : (value.length > 0 ? value : defaultValue)}
                    mode={mode}
                    onChange={this.handleChange}
                    onPanelChange={this.handlePanelChange}
                    onOpenChange={(open) => this.handleOpenChange(open,reset,changeReset)}
                />
            </Form.Item>
        );
    }
}

export default FormYearRangePicker;
